/**
 * huize Service Inc
 * All Rights Reserved @2018
 */
package com.hzins.zhike.okhttp3.simple;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * 描述: 配置重试策略
 *
 * @author tianyuliang
 * @version $Id: RetryInterceptor.java, v0.1 2022/4/14
 */
@Slf4j
public class RetryInterceptor implements Interceptor {

    /**
     * 最大重试次数
     */
    private int maxRetry;

    /**
     * 假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）
     */
    private int retryNum = 0;

    /**
     * 重试间隔 毫秒
     */
    private int retryInterval;

    public RetryInterceptor(int maxRetry, int retryInterval) {
        this.maxRetry = maxRetry;
        this.retryInterval = retryInterval;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        boolean ok1 = response != null && !response.isSuccessful();
        boolean ok2 = retryNum < maxRetry;
        while (ok1 && ok2) {
            retryNum++;
            log.info("[{}] retryNum ========> {} ", request.url().encodedPath(), retryNum);

            try {
                Thread.sleep(this.retryInterval);
            } catch (InterruptedException e) {
                log.error("retry interrupted error. msg={}", e.getMessage(), e);
            }
            response = chain.proceed(request);
        }
        return response;
    }

    public int getMaxRetry() {
        return maxRetry;
    }

    public int getRetryNum() {
        return retryNum;
    }

    public int getRetryInterval() {
        return retryInterval;
    }

}